<?php
// 引入头部
require_once 'includes/header.php';

// 获取当前页码
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page);
$limit = 10; // 每页显示10条
$offset = ($page - 1) * $limit;

// 获取查询条件
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-d');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');
$status = isset($_GET['status']) ? $_GET['status'] : 'completed';

// 构建查询条件
$conditions = [];
$params = [];

if (!empty($date_from)) {
    $conditions[] = "DATE(o.created_at) >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $conditions[] = "DATE(o.created_at) <= ?";
    $params[] = $date_to;
}

if ($status === 'all') {
    $conditions[] = "o.status IN ('completed', 'cancelled')";
} else if ($status === 'completed') {
    $conditions[] = "o.status = 'completed'";
} else if ($status === 'cancelled') {
    $conditions[] = "o.status = 'cancelled'";
}

$whereClause = '';
if (!empty($conditions)) {
    $whereClause = 'WHERE ' . implode(' AND ', $conditions);
}

// 获取总记录数
$count_sql = "SELECT COUNT(*) as total FROM orders o $whereClause";
$count_result = Database::fetch($count_sql, $params);
$total = $count_result ? $count_result['total'] : 0;

// 计算总页数
$total_pages = ceil($total / $limit);
// 确保页码不超过总页数
$page = min($page, max(1, $total_pages));

// 重新计算偏移量
$offset = ($page - 1) * $limit;

// 分页获取数据
$orders = [];
if ($total > 0) {
    $sql = "SELECT o.*, u.name as member_name 
            FROM orders o 
            LEFT JOIN users u ON o.user_id = u.id 
            $whereClause 
            ORDER BY o.created_at DESC 
            LIMIT $offset, $limit";
    $orders = Database::fetchAll($sql, $params);
}
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">历史订单</h5>
                </div>
                <div class="card-body">
                    <form method="GET" action="" class="form-inline">
                        <div class="form-group mb-2 mr-2">
                            <label for="date_from" class="mr-2">开始日期</label>
                            <input type="date" class="form-control" id="date_from" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
                        </div>
                        <div class="form-group mb-2 mr-2">
                            <label for="date_to" class="mr-2">结束日期</label>
                            <input type="date" class="form-control" id="date_to" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
                        </div>
                        <div class="form-group mb-2 mr-2">
                            <label for="status" class="mr-2">状态</label>
                            <select class="form-control" id="status" name="status">
                                <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>全部</option>
                                <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>已完成</option>
                                <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>已取消</option>
                            </select>
                        </div>
                        <button type="submit" class="btn btn-primary mb-2">查询</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <?php if (empty($orders)): ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i> 未找到符合条件的订单
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>订单号</th>
                                    <th>餐号</th>
                                    <th>金额</th>
                                    <th>支付方式</th>
                                    <th>会员</th>
                                    <th>状态</th>
                                    <th>时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($orders as $order): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($order['order_no']); ?></td>
                                    <td><?php echo htmlspecialchars($order['queue_number']); ?></td>
                                    <td>¥<?php echo number_format($order['actual_price'], 2); ?></td>
                                    <td>
                                        <?php
                                        switch ($order['payment_method']) {
                                            case 'cash': echo '现金'; break;
                                            case 'balance': echo '余额'; break;
                                            case 'wechat': echo '微信'; break;
                                            case 'alipay': echo '支付宝'; break;
                                            default: echo $order['payment_method']; break;
                                        }
                                        ?>
                                    </td>
                                    <td><?php echo $order['user_id'] ? htmlspecialchars($order['member_name']) : '非会员'; ?></td>
                                    <td>
                                        <?php
                                        switch ($order['status']) {
                                            case 'completed': 
                                                echo '<span class="badge badge-success">已完成</span>'; 
                                                break;
                                            case 'cancelled': 
                                                echo '<span class="badge badge-danger">已取消</span>'; 
                                                break;
                                            default: 
                                                echo '<span class="badge badge-secondary">' . $order['status'] . '</span>'; 
                                                break;
                                        }
                                        ?>
                                    </td>
                                    <td><?php echo date('m-d H:i', strtotime($order['created_at'])); ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-info view-order-btn" data-order-id="<?php echo $order['id']; ?>">
                                            <i class="fas fa-eye"></i> 详情
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页器 -->
                    <div class="pagination-container mt-4">
                        <nav aria-label="订单分页">
                            <ul class="pagination justify-content-center">
                                <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>">
                                        <i class="fas fa-angle-left"></i>
                                    </a>
                                </li>
                                <?php endif; ?>
                                
                                <?php
                                // 显示当前页码前后最多2页
                                $start_page = max(1, $page - 2);
                                $end_page = min($total_pages, $page + 2);
                                
                                for ($i = $start_page; $i <= $end_page; $i++):
                                ?>
                                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                                <?php endfor; ?>
                                
                                <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>">
                                        <i class="fas fa-angle-right"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $total_pages; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                                <?php endif; ?>
                            </ul>
                        </nav>
                        
                        <div class="text-center">
                            <small class="text-muted">共 <?php echo $total; ?> 条记录，<?php echo $total_pages; ?> 页</small>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 订单详情模态框 -->
<div class="modal fade" id="orderDetailModal" tabindex="-1" role="dialog" aria-labelledby="orderDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="orderDetailModalLabel">订单详情</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="order-detail-content">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                        <p class="mt-2">正在加载订单信息...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 查看订单详情
    const viewOrderBtns = document.querySelectorAll('.view-order-btn');
    viewOrderBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const orderId = this.dataset.orderId;
            $('#orderDetailModal').modal('show');
            
            // 加载订单详情
            fetch('/api/orders.php?action=get&id=' + orderId, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 构建订单详情HTML
                    const order = data.order;
                    const items = data.items;
                    
                    let itemsHtml = '';
                    let totalQuantity = 0;
                    
                    items.forEach(item => {
                        totalQuantity += parseInt(item.quantity);
                        itemsHtml += `
                            <tr>
                                <td>${item.product_name}</td>
                                <td>¥${parseFloat(item.price).toFixed(2)}</td>
                                <td>${item.quantity}</td>
                                <td>¥${parseFloat(item.subtotal).toFixed(2)}</td>
                                <td>
                                    ${item.status === 'pending' ? '<span class="badge badge-warning">待处理</span>' : 
                                      item.status === 'cooking' ? '<span class="badge badge-info">制作中</span>' : 
                                      item.status === 'completed' ? '<span class="badge badge-success">已完成</span>' : 
                                      '<span class="badge badge-secondary">' + item.status + '</span>'}
                                </td>
                            </tr>
                        `;
                    });
                    
                    const html = `
                        <div class="row">
                            <div class="col-md-6">
                                <h6>订单信息</h6>
                                <table class="table table-bordered">
                                    <tr>
                                        <th width="120">订单号</th>
                                        <td>${order.order_no}</td>
                                    </tr>
                                    <tr>
                                        <th>餐号</th>
                                        <td>${order.queue_number}</td>
                                    </tr>
                                    <tr>
                                        <th>状态</th>
                                        <td>
                                            ${order.status === 'completed' ? '<span class="badge badge-success">已完成</span>' : 
                                              order.status === 'cancelled' ? '<span class="badge badge-danger">已取消</span>' : 
                                              '<span class="badge badge-secondary">' + order.status + '</span>'}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>下单时间</th>
                                        <td>${new Date(order.created_at).toLocaleString()}</td>
                                    </tr>
                                    <tr>
                                        <th>备注</th>
                                        <td>${order.remark ? order.remark : '无'}</td>
                                    </tr>
                                </table>
                            </div>
                            
                            <div class="col-md-6">
                                <h6>金额信息</h6>
                                <table class="table table-bordered">
                                    <tr>
                                        <th width="120">总金额</th>
                                        <td>¥${parseFloat(order.total_price).toFixed(2)}</td>
                                    </tr>
                                    <tr>
                                        <th>优惠金额</th>
                                        <td>¥${parseFloat(order.discount_price).toFixed(2)}</td>
                                    </tr>
                                    <tr>
                                        <th>实付金额</th>
                                        <td class="text-danger font-weight-bold">¥${parseFloat(order.actual_price).toFixed(2)}</td>
                                    </tr>
                                    <tr>
                                        <th>支付方式</th>
                                        <td>
                                            ${order.payment_method === 'cash' ? '现金' : 
                                              order.payment_method === 'balance' ? '余额' : 
                                              order.payment_method === 'wechat' ? '微信' : 
                                              order.payment_method === 'alipay' ? '支付宝' : 
                                              order.payment_method}
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        
                        <h6>订单明细（共 ${totalQuantity} 件商品）</h6>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>商品</th>
                                        <th>单价</th>
                                        <th>数量</th>
                                        <th>小计</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${itemsHtml}
                                </tbody>
                            </table>
                        </div>
                    `;
                    
                    document.getElementById('order-detail-content').innerHTML = html;
                } else {
                    document.getElementById('order-detail-content').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle mr-2"></i> ${data.message || '获取订单信息失败'}
                        </div>
                    `;
                }
            })
            .catch(error => {
                document.getElementById('order-detail-content').innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle mr-2"></i> 请求发生错误: ${error}
                    </div>
                `;
            });
        });
    });
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 